import { createApp } from 'vue';
import { createPinia } from 'pinia';
import * as QianKun from 'qiankun';

import EnvConfig from '@core/utils/EnvConfig';
import Session from '@core/engine/Session';
import App from '@main/App.vue';
import SubAppHelper from '@main/utils/SubAppHelper';

import router from './utils/router';
import { i18n } from './i18n';
import GlobalState from '@/src/utils/GlobalState';

const render = async () => {
  const app = createApp(App);
  app.use(createPinia());
  app.use(i18n);
  await Session.init();
  GlobalState.init();
  await initQianKunConfigs();
  if (EnvConfig.isConnectToPublicPlatform()) {
    await Session.refreshMe();
  }
  app.use(router);
  app.mount('#app');
};

const initQianKunConfigs = () => {
  const subAppConfigs = SubAppHelper.getListForQianKun();
  subAppConfigs.forEach((subAppConfig) => {
    router.addRoute({
      path: `/${subAppConfig.name}`,
      name: subAppConfig.name,
      component: () => import('@main/components/layout/MainViewLayout.vue'),
      props: { isSubApp: true },
    });
  });
  QianKun.registerMicroApps(subAppConfigs);
  QianKun.addGlobalUncaughtErrorHandler((event) => {
    console.error('[qiankun] onGlobalUncaughtError', event);
  });
};

render();
